const { Add, Update, QueryOne, ExecGetOne, Exec, Query } = require('../db/dbhelper');
var { init, format } = require('../models/peoplefan');
var uninterested = require('../models/uinterested');
var { formatDate, formatDateTime, formatDateYear } = require('../libs/common');
var _ = require('underscore');
var { sendMsg } = require('./wechat');
const logger = require('../libs/log').logger;
var moment = require('moment');

//修改
const peoplefanUpdate = function (doc) {
  return Update('hzz_peoplefans', doc);
}
//收藏
const peoplefanFollow = async function (doc) {
  try {
    logger.info('--------peoplefanFollow-----收藏-------doc,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    if (!doc.fcode) {
      return {
        code: 1,
        msg: 'fcode参数不能为空'
      }
    }
    // 如果是本人，则返回
    if (doc.pcode == doc.fcode) {
      logger.info('--------peoplefanFollow-----自己无法收藏自己-------doc,', doc)
      return {
        code: 1,
        msg: '自己无法收藏自己'
      }
    }
    let data = await QueryOne('hzz_peoplefans', doc);
    doc.state = 1;
    let isok;
    if (data) {
      doc.id = data.id;
      isok = await Update('hzz_peoplefans', format(doc));
    } else {
      isok = await Add('hzz_peoplefans', init(doc));
    }
    if (isok) {
      let sql_token = `SELECT nickname FROM hzz_peoples  WHERE code = '${doc.fcode}' `;
      let fensi_data = await ExecGetOne(sql_token);
      if (fensi_data) {
        // 发送被收藏消息
        let send_data = {
          "first": {
            "value": "有人偷偷收藏了您，快去看看是谁吧！",
            "color": "#173177"
          },
          "keyword1": {
            "value": "好友收藏",
            "color": "#173177"
          },
          "keyword2": {
            "value": "TA可能对您有好感，当缘分来的时候要大胆抓住哦！",
            "color": "#173177"
          },
          "remark": {
            "value": "前往'消息-收藏我的'查看，感谢您的支持！",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "有人偷偷收藏了您，快去看看是谁吧！"
          },
          "time1": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('apppro_tmpid', send_data, doc.pcode, "pages/message/message",send_data_red);
        return {
          code: 0,
          msg: '收藏成功'
        };
      } else {
        return {
          code: 1,
          msg: '收藏失败,未找到粉丝信息'
        }
      }
    } else {
      return {
        code: 1,
        msg: '收藏失败,请稍后重试'
      }
    }
  } catch (error) {
    logger.info('--------peoplefanFollow-----收藏异常-------error,', error)
    return {
      code: 1,
      msg: error ? error.message : '收藏异常'
    }
  }
}

//取关
const peoplefanTakeoff = async function (doc) {
  try {
    logger.info('--------peoplefanTakeoff-----取关------doc,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    if (!doc.fcode) {
      return {
        code: 1,
        msg: 'fcode参数不能为空'
      }
    }
    let data = await QueryOne('hzz_peoplefans', doc);
    doc.state = 0;
    let isok;
    if (data) {
      doc.id = data.id;
      isok = await Update('hzz_peoplefans', format(doc));
    } else {
      isok = await Add('hzz_peoplefans', init(doc));
    }
    if (isok) {
      return {
        code: 0,
        msg: '取关成功'
      };
    } else {
      return {
        code: 1,
        msg: '取关失败,请稍后重试'
      }
    }
  } catch (error) {
    logger.error('--------peoplefanTakeoff-----取关异常-------error,', error)
    return {
      code: 1,
      msg: error ? error.message : '取关异常'
    }
  }
}

//收藏我的
const peoplefanMyfans = async function (doc) {
  try {
    logger.info('-----收藏我的---peoplefanMyfans------------doc,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    let filter = {
      state: 1,
      pcode: doc.pcode
    };
    let data = await Exec(`select * from hzz_peoplefans where pcode='${doc.pcode}' AND state=1  AND length(fcode)=12 ORDER BY createtime DESC,id DESC`);
    let peos = [];
    let myfans = [];
    if (data && data.length) {
      let codestr = _.pluck(data, 'fcode').join(',');
      let execsql = 'SELECT code,nickname,avator,grender,birthday,star,height,education,year_income,position,city,is_father FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
      // 我是否关注了收藏我的人
      myfans = await Exec(`SELECT pcode,fcode from hzz_peoplefans where fcode='${doc.pcode}'`);
    }
    let rdata = [];
    _.map(data, function (item) {
      item.state = 1; // 用户关注状态，1：关注我，2：互相关注
      item.updatetime = formatDateTime(item.createtime);
      delete item.createtime;
      // 更新关注状态
      let myf = _.find(myfans, function (po) {
        return po.pcode == item.fcode;
      });
      if (myf) {
        item.state = 2;
      }
      let people = _.find(peos, function (po) {
        return po.code == item.fcode;
      });
      if (people) {
        people.birthday = formatDateYear(people.birthday);
        if (people.city) {
          people.city = '现居' + people.city.replace('市', '');
        } else {
          people.city = '';
        }
        if (people.nickname && people.nickname.length > 6) {
          people.nickname = people.nickname.substr(0, 6);
        }
        // 用户没有头像，采用默认头像
        if(!people.avator){
          people.avator = people.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png': 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
        item.info = people || {};
        item.code = item.fcode;
        rdata.push(item);
        // 更新消息已读状态
        peoplefanUpdate({ id: item.id, pisread: 1 });
      }
    })
    return {
      code: 0,
      data: rdata
    };
  } catch (error) {
    logger.error('-----收藏我的---peoplefanMyfans-----获取异常-------error,', error)
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

//我的收藏
const peoplefanMyfollow = async function (doc) {
  try {
    logger.info('-----我的收藏---peoplefanMyfollow------------doc,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    let filter = {
      state: 1,
      fcode: doc.pcode
    };
    let data = await Exec(`select * from hzz_peoplefans where fcode='${doc.pcode}' AND state=1  AND length(pcode)=12 ORDER BY createtime DESC,id DESC`);;
    let peos = [];
    let fansme = [];
    if (data && data.length) {
      let codestr = _.pluck(data, 'pcode').join(',');
      let execsql = 'SELECT code,nickname,avator,age,grender,birthday,star,height,education,year_income,position,city FROM hzz_peoples WHERE CODE IN (' + codestr + ')';
      peos = await Exec(execsql);
      // 我是否关注了收藏我的人
      fansme = await Exec(`SELECT pcode,fcode from hzz_peoplefans where pcode='${doc.pcode}'`);
    }
    let rdata = [];
    _.map(data, function (item) {
      item.updatetime = formatDateTime(item.createtime);
      delete item.createtime;
      item.state = 1; // 用户关注状态，1：我关注，2：互相关注
      // 更新关注状态
      let myf = _.find(fansme, function (po) {
        return po.fcode == item.pcode;
      });
      if (myf) {
        item.state = 2;
      }
      let people = _.find(peos, function (po) {
        return po.code == item.pcode;
      })
      if (people) {
        people.birthday = formatDateYear(people.birthday);
        if (people.city) {
          people.city = '现居' + people.city.replace('市', '');
        } else {
          people.city = '';
        }
        if (people.nickname && people.nickname.length > 6) {
          people.nickname = people.nickname.substr(0, 6);
        }
        // 用户没有头像，采用默认头像
        if(!people.avator){
          people.avator = people.grender == '男' ? 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/male_a.png': 'https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png';
        }
        item.info = people;
        item.code = item.pcode;
        rdata.push(item);
        // 更新消息已读状态
        peoplefanUpdate({ id: item.id, fisread: 1 });
      }
    })
    return {
      code: 0,
      data: rdata
    };
  } catch (error) {
    logger.error('-----我的收藏---peoplefanMyfollow-----获取异常-------error,', error)
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

//不感兴趣
const peopleUninterested = async function (doc) {
  try {
    logger.info('--------peopleUninterested-----不感兴趣-------doc,', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数不能为空'
      }
    }
    if (!doc.fcode) {
      return {
        code: 1,
        msg: 'fcode参数不能为空'
      }
    }
    // 如果是本人，则返回
    if (doc.pcode == doc.fcode) {
      logger.info('--------peopleUninterested-----自己无法操作自己-------doc,', doc)
      return {
        code: 1,
        msg: '自己无法操作自己'
      }
    }
    let data = await QueryOne('hzz_uinteresteds', doc);
    if (!data) {
      await Add('hzz_uinteresteds', uninterested.init(doc));
    }
    // 移除推荐列表
    let now = new Date();
    let builddate = formatDate(now);
    await Exec(`delete from hzz_dailyusers  where pcode='${doc.fcode}' AND tcode='${doc.pcode}' AND builddate='${builddate}'`)
    return {
      code: 0,
      msg: ''
    }
  } catch (error) {
    logger.error('--------peopleUninterested-----不感兴趣-------error,', error)
    return {
      code: 1,
      msg: '拉黑失败，请联系客服'
    }
  }
}

module.exports = {
  peoplefanFollow,
  peoplefanTakeoff,
  peoplefanMyfans,
  peoplefanMyfollow,
  peopleUninterested
}